import cv2
import numpy as np
import capimg
import time


def getCamBindBox(img):

    # 加载彩色图像
    # baseimg = cv2.imread('test.jpg')
    # _res,baseimg = capimg.camImg()

    # 转换为灰度图像
    image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # 加载灰度图像
    # 设置灰度阈值范围
    threshold_min = 100
    threshold_max = 200

    # 应用灰度阈值
    ret, thresh = cv2.threshold(image, threshold_min, threshold_max, cv2.THRESH_BINARY)

    # 运行形态学操作（可选）
    kernel = np.ones((5, 5), np.uint8)
    thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)

    # 查找边界直线
    edges = cv2.Canny(thresh, 50, 150, apertureSize=3)
    lines = cv2.HoughLinesP(edges, 1, np.pi / 180, threshold=100, minLineLength=100, maxLineGap=10)

    # 创建一个彩色图像，用于可视化直线
    color_image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
    # # 绘制检测到的直线
    # if  lines is not None:
    #     # print(len(lines))
    #     for line in lines:
    #         x1, y1, x2, y2 = line[0]
    #         cv2.line(color_image, (x1, y1), (x2, y2), (0, 255, 0), 2)
    #     #     print(line)
    # else:
    #     print('no line')
   
    # 显示结果
    return color_image,lines

    cv2.imshow('Color Boundary Lines', color_image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

def resizeImg(img,suofang = 3.0):
    height, width = img.shape[:2]
    down_points = (int(width/suofang), int(height/suofang))
    color_image =  cv2.resize(img, down_points, interpolation= cv2.INTER_LINEAR)
    return color_image

#找出所有直线线段端点中最远的两个点,并生成一条新的线,并绘制出来
def testLinesInBox(lines,spt,ept):
    pass

def test():
    isConvent = False
    isStopCap = False
    cv2WinName = 'caminit'
    spt = None
    ept = None
    lines = []
    bimg = None
    def on_Event_mouse(event, x, y,flags, param):
        #左键按下
        if event == cv2.EVENT_LBUTTONDOWN:
            # self.mPressFunc(x,y,flags)
            spt = (x,y)
        #左键抬起
        elif event == cv2.EVENT_LBUTTONUP:
            # self.mReleaseFunc(x,y,flags)
            ept = (x,y)
        #鼠标移动
        elif event == cv2.EVENT_MOUSEMOVE:
            # self.mMoveFunc(x,y,flags)
            pass
    cv2.namedWindow(cv2WinName)
    cv2.setMouseCallback(cv2WinName, on_Event_mouse)
    fps = 0
    dt = 0
    while True:
        if isStopCap:
            img,_lines = getCamBindBox(bimg)
            if  lines is not None:
                for line in lines:
                    x1, y1, x2, y2 = line[0]
                    cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
        else:
            _res,bimg = capimg.camImg('PC Camera')
            if isConvent:
                img,lines = getCamBindBox(bimg)
                # 绘制检测到的直线
                if  lines is not None:
                    for line in lines:
                        x1, y1, x2, y2 = line[0]
                        cv2.line(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
            else:
                img = bimg
        #缩放图片,以方便显示
        # img = resizeImg(img)
        cv2.imshow(cv2WinName, img)
        nt = time.time()
        if nt - dt >= 1:
            dt = nt
            print(fps)
            fps = 0
        else:
            fps = fps + 1
        # print(fps,nt)
        key = cv2.waitKey(1)
        if key > 0:
            if key & 0xFF == 0x1B:
                exit(0)
            elif key & 0xFF == ord('s'):#s,停止使用新图像
                isStopCap = True
            elif key & 0xFF == ord('r'):#r,开始使用新图像
                isStopCap = False
            elif key & 0xFF == 0x20: #空格
                isConvent = not isConvent

if __name__ == '__main__':  
    # test2()
    test()
    
# ————————————————
# 版权声明：本文为CSDN博主「QQQQQYE」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
# 原文链接：https://blog.csdn.net/qinye101/article/details/120000500